package com.goodsogood.union.auth.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dongguochao.validation.annotation.Valid;
import com.goodsogood.tool.result.ResponseResult;
import com.goodsogood.union.auth.conf.LogConfiger;
import com.goodsogood.union.auth.service.AuthService;
import com.goodsogood.union.auth.web.validator.AuthAndTokenValidator;
import com.goodsogood.union.auth.web.validator.TokenGenerateValidator;
import com.goodsogood.union.auth.web.validator.TokenParamValidator;

/**
 * 手机api模块
 */
@Controller
@RequestMapping("/authentication")
public class AuthController {
	private static final Logger logger = LoggerFactory.getLogger(LogConfiger.APP);
	@Autowired
	private AuthService authService;
	
	@Valid(TokenGenerateValidator.class)
	@ResponseBody
	@RequestMapping(value = "/getAccessToken")
	public String getAccessToken(@RequestParam Map<String, String> filter, HttpServletRequest request) {
		try {
			return JSON.toJSONString(authService.tokenGenerate(filter.get("plateformDeviceType"), filter.get("userId") ,filter.get("plateformDeviceInfo") ));
		} catch (Exception e) {
			logger.error("token生成失败。" , e );
			return JSON.toJSONString(ResponseResult.failInstance("token生成失败"));
		}
	}

	@Valid(TokenParamValidator.class)
	@ResponseBody
	@RequestMapping(value = "/tokenCheck")
	public String check(@RequestParam Map<String, String> filter, HttpServletRequest request) {
		try {
			return JSON.toJSONString(authService.checkToken(filter, request));
		} catch (Exception e) {
			logger.error(" token校验失败!" , e );
			return JSON.toJSONString(ResponseResult.failInstance("token校验失败"));
		}
	}

	@ResponseBody
	@RequestMapping(value = "/ping")
	public String ping(@RequestParam Map<String, String> filter) {
		return "ok";
	}
	/**验证后台用户的权限*/
	@Valid(AuthAndTokenValidator.class)
	@ResponseBody
	@RequestMapping(value = "/checkAuthAndToken")
	public String checkAuthAndToken(@RequestParam Map<String, String> filter, HttpServletRequest request) {
		try {
			return JSON.toJSONString(authService.checkAuthAndToken(filter));
		} catch (Exception e) {
			logger.error("token生成失败。" , e );
			return JSON.toJSONString(ResponseResult.failInstance("token生成失败"));
		}
	}
}
